%% The MIT License
%% 
%% Paralog is licensed under the MIT License.
%% 
%% Copyright (c) 2008 Robert Ahrens <mindangels@yahoo.com>
%% 
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), to deal
%% in the Software without restriction, including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%% copies of the Software, and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%% 
%% The above copyright notice and this permission notice shall be included in
%% all copies or substantial portions of the Software.
%% 
%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%% THE SOFTWARE.
%% 

%% @author 
-module(gs_kb_server).
-behaviour(gen_server).


%% Simple gen_server for knowledge-base serving.

-export([
         init/1,
         handle_call/3,
         handle_cast/2,
         handle_info/2,
         terminate/2,
         code_change/3,
         start_new/0
        ]).


-record(state, {db=[]}).


%%% Public API

start_new() ->
    case gen_server:start(?MODULE, [], [])  of
        {ok, Pid} ->
            ets_kb:new(Pid);
        Error ->
            throw({error, Error})
    end.


%%% gen_server callbacks
init([]) ->
    {ok, #state{}}.


handle_call({lookup, RuleName, Arity}, _From, State=#state{db=DB})
  when is_atom(RuleName) andalso is_integer(Arity) ->
    {reply, [R || R={_, Name, Head, _} <- DB,
                  Name =:= RuleName,
                  length(Head) == Arity], State}.


handle_cast({load, Rules}, #state{db=DB}) ->
    {noreply, #state{db=DB ++ Rules}};
handle_cast({asserta, Rule}, #state{db=DB}) ->
    {noreply, #state{db=[Rule|DB]}};
handle_cast({assertz, Rule}, #state{db=DB}) ->
    {noreply, #state{db=DB ++ [Rule]}};
handle_cast(stop, State) ->
    {stop, normal, State}.


handle_info(_, State) ->
    {noreply, State}.


terminate(normal, #state{db=DB}) ->
    io:format("terminate called with DB = ~p~n", [DB]),
    ok.


code_change(_, State, _) ->
    {ok, State}.


%%% internal functions
